# (1)	通过OpenCV完成划痕检测并标记
#  题目要求：
# ①　导入相关头文件
import cv2 as cv
import numpy as np

np.random.seed(1)


def rand_color():
    return (
        np.random.randint(0, 256),
        np.random.randint(0, 256),
        np.random.randint(0, 256),
    )


# ②　读取图片
img = cv.imread('data/huahen.png', cv.IMREAD_COLOR)
cv.imshow('ori', img)

# ③　均值滤波
# ④　均值滤波器核设置合理
kernel = np.full([3, 3], 1./9.)
blur = cv.filter2D(img, cv.CV_32F, kernel)
cv.normalize(blur, blur, 0, 255, cv.NORM_MINMAX)
blur = np.uint8(blur)
cv.imshow('blur', blur)

# ⑤　原图和均值图进行作差得到差分图像
diff = cv.subtract(blur, img)
cv.imshow('diff', diff)

# ⑥　完成二值化
gray = cv.cvtColor(diff, cv.COLOR_BGR2GRAY)
ret, bin = cv.threshold(gray, 0, 255, cv.THRESH_OTSU + cv.THRESH_BINARY_INV)
# ret, bin = cv.threshold(gray, 25, 255, cv.THRESH_BINARY_INV)

# ⑦　显示二值图
cv.imshow('bin', bin)

# ⑧　设置保存轮廓的容器
bg = np.zeros_like(img)

# ⑨　完成轮廓的提取
contours, hierarchy = cv.findContours(bin, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
for c in contours:
    cv.drawContours(bg, [c], 0, rand_color())
cv.imshow('contours', bg)

# ⑩　轮廓过滤
result_contours = []
for c in contours:
    rect = cv.minAreaRect(c)

# 11　进行轮廓绘制
# 12　计算轮廓的周长
# 13　在轮廓周围写上12计算出的长度，格式为，“划痕缺陷长度：”

cv.waitKey(0)
cv.destroyAllWindows()
